import sys
import urlparse
import string
import StringIO

class WSGIEnvironment():
    """
    Server Side Environment
    """
    def __init__(self):
        self.debug = False
        self.dict = {}

        self.dict['SERVER_NAME'] = 'WSGI Container'
        self.dict['SERVER_SOFTWARE'] = 'WSGI Container/1.0'
        self.dict['GATEWAY_INTERFACE'] = 'CGI/1.1'
        self.dict['REMOTE_HOST'] ='wsgicontainer'
        self.dict['CONTENT_LENGTH']=''
        self.dict['SCRIPT_NAME'] = ''
        self.dict['PATH_INFO'] = '/'
        self.dict['HTTP_COOKIE'] = ''
        self.dict['REQUEST_METHOD'] = 'GET'
        self.dict['QUERY_STRING'] = ''
        self.dict['SERVER_PROTOCOL'] = 'HTTP/1.1'
        self.dict['HTTP_HOST'] = ''
        self.dict['SERVER_PORT'] = '80'

        self.dict['wsgi.input'] = sys.stdin
        self.dict['wsgi.errors'] = sys.stdout
        self.dict['wsgi.version'] = (1, 0)
        self.dict['wsgi.run_once'] = False
        self.dict['wsgi.url_scheme'] = 'http'
        self.dict['wsgi.multithread'] = True
        self.dict['wsgi.multiprocess'] = False

    def __str__(self):
        return self.dict

    def setvalue(self, key, value):
        self.dict[key] = value

    def seturi(self, value):
        uritpl = urlparse.urlparse(value)
        self.dict['PATH_INFO'] = uritpl[2]
        if uritpl[5]:
            self.dict['QUERY_STRING'] = string.join(uritpl[4:], '#')
        else:
            self.dict['QUERY_STRING'] = uritpl[4]

    def setcookie(self, value):
        if value:
            self.dict['HTTP_COOKIE'] = value

    def setpost(self, value):
        if value:
            self.dict['REQUEST_METHOD'] = 'POST'
            self.dict['CONTENT_TYPE'] = 'application/x-www-form-unlecoded'
            self.dict['CONTENT_LENGTH'] = len(value)
            self.dict['wsgi.input'] = StringIO.StringIO(value)
